package com.iflytek.aidemo;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;

import com.iflytek.aidemo.model.User;
import com.iflytek.aidemo.student.WrongQuestionActivity;
import com.iflytek.aidemo.util.SessionManager;
import com.iflytek.aidemo.teacher.TeacherScoreOverviewActivity;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    public static final int TAKE_PHOTO = 1;
    public static final int CHOOSE_PHOTO = 2;

    /*用来记录录像存储路径*/
    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/video.mp4");//设置录像存储路径
    Uri uri = Uri.fromFile(file);//文件转成Uri格式

    private FrameLayout takePhotoContainer;
    private ImageView rippleEffect;
    private AnimatorSet blinkAnimator;
    private AnimatorSet rippleAnimator;
    private TextView tvWelcome, tvUserType;
    private SessionManager sessionManager;
    private ImageButton btnLogout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 初始化SessionManager
        sessionManager = new SessionManager(this);
        
        // 根据用户身份选择不同的布局
        setLayoutBasedOnUserType();
        
        // 初始化视图
        initViews();

        // 返回按钮（如果布局中存在）
        View back = findViewById(R.id.btn_back);
        if (back != null) {
            back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
        
        // 显示用户信息
        displayUserInfo();
        
        // 创建闪烁动画
        createBlinkAnimation();
        
        // 创建波纹动画
        createRippleAnimation();

        // 启动闪烁动画
        startBlinkAnimation();
        
        // 启动波纹动画
        startRippleAnimation();

        //对照相功能的响应
        Button takePhoto = findViewById(R.id.take_photo);
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 停止闪烁动画
                stopBlinkAnimation();
                
                // 停止波纹动画
                stopRippleAnimation();
                
                // 添加点击动画效果
                addClickAnimation(v);
                
                // 延迟执行跳转，让动画效果显示
                v.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 在新的Intent里面打开，并且传递TAKE_PHOTO选项
                        Intent intent = new Intent();
                        intent.setClass(MainActivity.this, ImageAlbumShow.class);//也可以这样写intent.setClass(MainActivity.this, OtherActivity.class);

                        Bundle bundle = new Bundle();
                        bundle.putInt("id", TAKE_PHOTO);//使用显式Intent传递参数，用以区分功能
                        intent.putExtras(bundle);

                        MainActivity.this.startActivity(intent);//启动新的Intent
                    }
                }, 200);
            }
        });

        //设置相册选择的响应
        Button chooseFromAlbum = findViewById(R.id.choose_from_album);
        chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 添加点击动画效果
                addClickAnimation(v);
                
                // 延迟执行跳转，让动画效果显示
                v.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 在新的Intent里面打开，并且传递CHOOSE_PHOTO选项
                        Intent intent = new Intent();
                        intent.setClass(MainActivity.this, ImageAlbumShow.class);//也可以这样写intent.setClass(MainActivity.this, OtherActivity.class);

                        Bundle bundle = new Bundle();
                        bundle.putInt("id", CHOOSE_PHOTO);
                        intent.putExtras(bundle);

                        MainActivity.this.startActivity(intent);
                    }
                }, 200);
            }
        });

        btnLogout = findViewById(R.id.btn_logout);
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new android.app.AlertDialog.Builder(MainActivity.this)
                    .setTitle("确认登出")
                    .setMessage("您确定要退出登录吗？")
                    .setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(android.content.DialogInterface dialog, int which) {
                            sessionManager.clearSession();
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                            finish();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
            }
        });

        // 错题集按钮点击事件
        ImageView btnWrongBook = findViewById(R.id.btn_wrong_book);
        if (btnWrongBook != null) {
            btnWrongBook.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    User currentUser = sessionManager.getCurrentUser();
                    if (currentUser != null) {
                        Intent intent = new Intent(MainActivity.this, WrongQuestionActivity.class);
                        intent.putExtra("student_id", currentUser.getUserId());
                        startActivity(intent);
                    }
                }
            });
        }

        // 老师端：查看成绩按钮
        Button btnViewScores = findViewById(R.id.btn_view_scores);
        if (btnViewScores != null) {
            btnViewScores.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, TeacherScoreOverviewActivity.class);
                    startActivity(intent);
                }
            });
        }
    }

    /**
     * 根据用户身份设置布局
     */
    private void setLayoutBasedOnUserType() {
        User currentUser = sessionManager.getCurrentUser();
        if (currentUser != null) {
            String userType = currentUser.getUserType();
            if (userType != null && !userType.isEmpty()) {
                if (userType.equals("1")) {
                    // 学生身份
                    setContentView(R.layout.activity_main_student);
                } else {
                    // 老师身份
                    setContentView(R.layout.activity_main_teacher);
                }
            } else {
                // 默认使用学生布局
                setContentView(R.layout.activity_main_student);
            }
        } else {
            // 默认使用学生布局
            setContentView(R.layout.activity_main_student);
        }
    }

    /**
     * 初始化视图
     */
    private void initViews() {
        takePhotoContainer = findViewById(R.id.take_photo_container);
        rippleEffect = findViewById(R.id.ripple_effect);
        tvWelcome = findViewById(R.id.tv_welcome);
        tvUserType = findViewById(R.id.tv_user_type);
    }

    /**
     * 显示用户信息
     */
    private void displayUserInfo() {
        User currentUser = sessionManager.getCurrentUser();
        if (currentUser != null) {
            String username = currentUser.getUserName();
            String userType = currentUser.getUserType();
            
            // 设置欢迎信息
            tvWelcome.setText(" 欢迎，" + username + "！");
            
            // 设置用户类型信息和头像
            if (userType != null && !userType.isEmpty()) {
                com.iflytek.aidemo.util.CircleImageView ivAvatar = findViewById(R.id.iv_avatar);
                if (ivAvatar != null) {
                    if (userType.equals("1")) {
                        // 学生身份
                        tvUserType.setText("当前身份：学生");
                        ivAvatar.setImageResource(R.mipmap.student);
                    } else {
                        // 老师身份
                        tvUserType.setText("当前身份：老师");
                        ivAvatar.setImageResource(R.mipmap.teacher);
                    }
                }
            } else {
                tvUserType.setText("当前身份：未知");
            }
        } else {
            tvWelcome.setText("欢迎使用！");
            tvUserType.setText("当前身份：未知");
        }
    }

    /**
     * 创建闪烁动画
     */
    private void createBlinkAnimation() {
        // 透明度动画 - 更平滑的效果
        ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(takePhotoContainer, "alpha", 1.0f, 0.7f, 1.0f);
        alphaAnimator.setDuration(2000);
        alphaAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        alphaAnimator.setRepeatMode(ObjectAnimator.RESTART);

        // 缩放动画 - 脉冲效果
        ObjectAnimator scaleXAnimator = ObjectAnimator.ofFloat(takePhotoContainer, "scaleX", 1.0f, 1.02f, 1.0f);
        scaleXAnimator.setDuration(2000);
        scaleXAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        scaleXAnimator.setRepeatMode(ObjectAnimator.RESTART);

        ObjectAnimator scaleYAnimator = ObjectAnimator.ofFloat(takePhotoContainer, "scaleY", 1.0f, 1.02f, 1.0f);
        scaleYAnimator.setDuration(2000);
        scaleYAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        scaleYAnimator.setRepeatMode(ObjectAnimator.RESTART);

        // 组合动画
        blinkAnimator = new AnimatorSet();
        blinkAnimator.playTogether(alphaAnimator, scaleXAnimator, scaleYAnimator);
        blinkAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
    }

    /**
     * 创建波纹动画
     */
    private void createRippleAnimation() {
        // 波纹缩放动画
        ObjectAnimator rippleScaleX = ObjectAnimator.ofFloat(rippleEffect, "scaleX", 0.8f, 1.3f, 0.8f);
        rippleScaleX.setDuration(2000);
        rippleScaleX.setRepeatCount(ObjectAnimator.INFINITE);
        rippleScaleX.setRepeatMode(ObjectAnimator.RESTART);

        ObjectAnimator rippleScaleY = ObjectAnimator.ofFloat(rippleEffect, "scaleY", 0.8f, 1.3f, 0.8f);
        rippleScaleY.setDuration(2000);
        rippleScaleY.setRepeatCount(ObjectAnimator.INFINITE);
        rippleScaleY.setRepeatMode(ObjectAnimator.RESTART);

        // 波纹透明度动画
        ObjectAnimator rippleAlpha = ObjectAnimator.ofFloat(rippleEffect, "alpha", 0.2f, 0.8f, 0.2f);
        rippleAlpha.setDuration(2000);
        rippleAlpha.setRepeatCount(ObjectAnimator.INFINITE);
        rippleAlpha.setRepeatMode(ObjectAnimator.RESTART);

        // 波纹旋转动画
        ObjectAnimator rippleRotation = ObjectAnimator.ofFloat(rippleEffect, "rotation", 0f, 360f);
        rippleRotation.setDuration(4000);
        rippleRotation.setRepeatCount(ObjectAnimator.INFINITE);
        rippleRotation.setRepeatMode(ObjectAnimator.RESTART);

        // 组合波纹动画
        rippleAnimator = new AnimatorSet();
        rippleAnimator.playTogether(rippleScaleX, rippleScaleY, rippleAlpha, rippleRotation);
        rippleAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
    }

    /**
     * 启动闪烁动画
     */
    private void startBlinkAnimation() {
        if (blinkAnimator != null && !blinkAnimator.isRunning()) {
            blinkAnimator.start();
        }
    }

    /**
     * 启动波纹动画
     */
    private void startRippleAnimation() {
        if (rippleAnimator != null && !rippleAnimator.isRunning()) {
            rippleAnimator.start();
        }
    }

    /**
     * 停止闪烁动画
     */
    private void stopBlinkAnimation() {
        if (blinkAnimator != null && blinkAnimator.isRunning()) {
            blinkAnimator.cancel();
        }
    }

    /**
     * 停止波纹动画
     */
    private void stopRippleAnimation() {
        if (rippleAnimator != null && rippleAnimator.isRunning()) {
            rippleAnimator.cancel();
        }
    }

    /**
     * 添加点击动画效果
     */
    private void addClickAnimation(View view) {
        // 缩放动画
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1.0f, 0.95f, 1.0f);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1.0f, 0.95f, 1.0f);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scaleX).with(scaleY);
        animatorSet.setDuration(150);
        animatorSet.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 重新启动动画
        startBlinkAnimation();
        startRippleAnimation();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 停止动画
        stopBlinkAnimation();
        stopRippleAnimation();
    }
}